#include "videopage.h"
#include <QGridLayout>
#include <phonon/videowidget.h>
#include <phonon/seekslider.h>
#include <QListWidget>
#include <phonon/mediaobject.h>


VideoPage::VideoPage(QWidget *parent, Video *video)
        : QWidget(parent),
        m_video(video)
{
    QGridLayout *layout = new QGridLayout(this);
    setLayout(layout);

    m_video = video;
    m_player = new Phonon::VideoPlayer(Phonon::VideoCategory, this);
    m_player->videoWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);

    Phonon::SeekSlider *slider = new Phonon::SeekSlider;
    slider->setMediaObject(m_player->mediaObject());
    slider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    QListWidget *fileList = new QListWidget(this);
    fileList->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

    m_playPauseButton = new QPushButton(QIcon("media-playback-start.png"), "");
    connect(m_playPauseButton, SIGNAL(clicked()), SLOT(togglePlay()));

    layout->addWidget(m_player->videoWidget(), 0, 0, 1, 2);
    layout->addWidget(slider, 1, 0);
    layout->addWidget(m_playPauseButton, 1, 1);
    layout->addWidget(fileList, 2, 0, 1, 2);

    foreach(QUrl file, m_video->files())
        fileList->addItem(file.toLocalFile());

    connect(fileList, SIGNAL(doubleClicked(QModelIndex)), SLOT(playFile(QModelIndex)));
}

VideoPage::~VideoPage()
{
    m_video->open = false;
    delete m_playPauseButton;
}

void VideoPage::playFile(QModelIndex index)
{
    m_player->play(index.data().toString());
}

void VideoPage::togglePlay()
{
    if (m_player->isPlaying())
        m_player->pause();
    else if (m_player->mediaObject()->currentSource().url().isEmpty())
        m_player->play(m_video->files()[0]);
    else
        m_player->play();

}
